package com.ada;

import com.itextpdf.text.pdf.BaseFont;
import com.lowagie.text.DocumentException;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;

/**
 * @author ada
 * @date 2022/4/27
 */
public class XhtmlrendererApp {

    public static void main(String[] args) throws ParserConfigurationException, IOException, DocumentException {
        InputStream stream = null;
        HttpResponse response = HttpRequest.get("http://www.he1618.com/onlineShoppingMall/onlineStore").send();
        stream = new ByteArrayInputStream(response.bodyBytes());

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        System.out.println("=========================>文档编译器初始化完成");
        Document doc=null;
        try{
            doc= builder.parse(stream);
        }catch (Exception ex){
            System.out.println("初始化doc异常，异常信息如下");
            ex.printStackTrace();
        }
        System.out.println("======================================>文档创建完成");
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(doc, null);
        System.out.println("======================================>文档读取完成");
        // 解决中文支持问题
        ITextFontResolver fontResolver = renderer.getFontResolver();
        String fontFile=null;
        System.out.println("======================================>解决中文问题，字体路径为："+fontFile);
        String simusun = fontFile;
        if (simusun != null) {
            String type="win";
            if(type.trim().equals("linux")){
                fontResolver.addFont(simusun, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            }else{
                fontResolver.addFont(simusun, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }
        }
        System.out.println("======================================>文档中文信息已解决");
        // 解决图片的相对路径问题
        String basePath="";
        renderer.getSharedContext().setBaseURL("file:" + basePath);
        renderer.layout();
        System.out.println("======================================>图片路径已经替换完成");
        //返回PDF字节数组 一边上传文件服务器
        ByteArrayOutputStream os = new ByteArrayOutputStream(1024000);
        renderer.createPDF(os);
        System.out.println("======================================>pdf文件创建文档流完成");
        //输出PDF文件，文件到指定目录
        String outPath="e:\\output.pdf";
        OutputStream fileStream = new FileOutputStream(outPath);
        fileStream.write(os.toByteArray());
        fileStream.flush();
        fileStream.close();
    }

}
